package controllers.manage.product;

import controllers.BaseController;
import controllers.auth.Secure;
import controllers.auth.SkipAuth;
import enums.ProductStatus;
import enums.ReviewStatus;
import helper.AliyunOssUploader;
import helper.GlobalConfig;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.merchant.enums.VerifyState;
import models.msgtemp.admin.WxMpAdminMsgTemp;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.Controller;
import play.mvc.With;
import product.Product;
import product.ProductImage;
import product.type.ProductType;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品管理
 * Created by buhaoba on 2017/4/6.
 */
@With(BaseController.class)
public class ProductCtrl extends Controller {


    /**
     * 跳转到产品管理页面
     */
    public static void index(Integer pageNumber, String name, String merchantName) {



        pageNumber = pageNumber == null ? 1 : pageNumber;
        Map<String , Object> searchMap = new HashMap<>();

        if(StringUtils.isNotBlank(name)){
            searchMap.put("name", "%"+name+"%");
        }

        if(StringUtils.isNotBlank(merchantName)){
            searchMap.put("merchantName", "%"+merchantName+"%");
        }

        searchMap.put("verifyState", VerifyState.PASS);
        searchMap.put("productStatus", ProductStatus.UP);
        searchMap.put("reviewStatus", ReviewStatus.NORMAL);
        flash.put("menuId", "19");

        JPAExtPaginator<Product> resultPage = Product.findByCondition(searchMap, "id desc", pageNumber, GlobalConfig.PAGE_SIZE);
        render(resultPage, pageNumber,name,merchantName);
    }

    /**
     * 跳转到添加产品页面
     */
    public static void add() {
        Merchant merchant = Secure.getLoginUser().merchant;
        List<ProductType> productTypes = ProductType.findAllProductTypes(merchant.id);
        render(productTypes);
    }

    /**
     * 跳转到修改产品页面
     */
    public static void modify(long id, Integer pageNumber){
        List<ProductType> productTypes = ProductType.loadAllType();
        Product product = Product.findById(id);
        List<ProductImage> productImageList = ProductImage.loadByProductId(id);
        render(product, pageNumber, productTypes,productImageList);
    }

    /**
     * 创建产品
     * @param product
     */
    public static void create(Product product , File mainImage) {

        Merchant merchant = Secure.getLoginUser().merchant;
        product.merchant = merchant;

        Logger.info("create  mainImage : %s" , mainImage);
        try {
            if(mainImage != null) {
                BufferedImage sourceImg = ImageIO.read(new FileInputStream(mainImage));
                Integer width = sourceImg.getWidth();
                Integer height = sourceImg.getHeight();
                if(((double)width/(double)height) != ((double)4/(double)3)){
                    product.deleted = DeletedStatus.UN_DELETED;
                    product.save();
                    flash.put("msg" , "图片比例不是4:3");
                    modify(product.id, 1);
                }
                product.mainImage = AliyunOssUploader.uploadPublicFile(mainImage , 300);
            }
            product.deleted = DeletedStatus.UN_DELETED;
            product.save();
            flash.put("msg" , "产品创建成功");
            redirect("/BS0019/admin/product/index/1");
        } catch (Exception e) {
            Logger.warn(e, "LOG01750: product create failed!");
        }
    }

    /**
     * 修改产品
     */
    public static void update(Long id, Product product, Integer pageNumber,File mainImage){
        try {
            Product newPro = Product.findByProductId(id);
            newPro.weightValue = product.weightValue;
            newPro.save();
          //  AliyunOpenSearch.uploadProductByRiZhi(newPro);
            flash.put("msg" , "产品修改成功");
            redirect("/BS0019/admin/product/index/"+pageNumber);
        } catch (Exception e) {
            Logger.warn(e, "LOG01750: product create failed!");
        }
    }

    /**
     * 删除产品
     */
    public static void delete(long id , Integer pageNumber){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        Product product = Product.findById(id);
        product.deleted=DeletedStatus.DELETED;
        product.save();
        flash.put("msg" , "产品删除成功");
        redirect("/BS0019/admin/product/index/"+pageNumber);
    }

    @SkipAuth
    public static void popProduct(Integer pageNumber , String name, Long parentType,Long productType , String merchantName , ProductStatus productStatus){
//        Merchant merchant = Secure.getLoginUser().merchant;
        Logger.info("parentType : %s" , parentType);
        Logger.info("productType : %s" , productType);

        pageNumber = pageNumber == null ? 1 : pageNumber;
        Map<String , Object> searchMap = new HashMap<>();
        searchMap.put("verifyState", VerifyState.PASS); // 选择审核通过的商户的产品

        if(StringUtils.isNotBlank(name)){
            searchMap.put("name", "%"+name+"%");
        }


        if(parentType != null){
            searchMap.put("parentType", parentType);
        }


        if(productType != null){
            searchMap.put("productType", productType);
        }


        if(StringUtils.isNotBlank(merchantName)){
            searchMap.put("merchantName", "%"+merchantName+"%");
        }


        if(productStatus == null){
            searchMap.put("productStatus", ProductStatus.UP);
        }


        List<ProductType>  parentTypeList = ProductType.findChildNode(0);
        List<ProductType>  typeList = new ArrayList<>();
        if(parentType != null){
             typeList = ProductType.findChildNode(parentType);
        }


        JPAExtPaginator<Product> resultPage = Product.findByCondition(searchMap, "productType.id ", pageNumber, GlobalConfig.PAGE_SIZE);

        Logger.info("resultPage : %s" , resultPage.size());

        render(resultPage, pageNumber , name , productType , merchantName , parentType,parentTypeList,typeList);
    }

    /**
     * 跳转到修改产品页面
     */
    public static void frozen(long id, Integer pageNumber){
        List<ProductType> productTypes = ProductType.loadAllType();
        Product product = Product.findById(id);
        render(product, pageNumber, productTypes);
    }

    public static  void  frozenProduct(Long id, Integer pageNumber){
        Product product = Product.findByProductId(id);
        product.reviewStatus = ReviewStatus.FROZEN;
      //  AliyunOpenSearch.uploadProductByRiZhi(product);
        WxMpAdminMsgTemp.sendMsgforFreezingProduct(product);
        Product.update(id , product);
        flash.put("msg" , "冻结产品成功");
        redirect("/BS0019/admin/product/index/"+pageNumber);
    }

    /**
     * 跳转产品权重修改
     */
    public static void modifyWeight(long id, Integer pageNumber){
        List<ProductImage> productImageList = ProductImage.loadByProductId(id);
        List<ProductType> productTypes = ProductType.loadAllType();
        Product product = Product.findById(id);
        render(product, pageNumber, productTypes,productImageList);
    }


    /**
     * 二级分类
     * @param id
     */
    public static void secondLevel(long id){
        Map<String , Object> resultMap = new HashMap<>();
        if(id == 0){
            resultMap.put("success",false);
            resultMap.put("list", new ArrayList<ProductType>());
            renderJSON(resultMap);
        }
        List<ProductType> secondLevel = ProductType.findChildNode(id);
        if(secondLevel == null || secondLevel.size() == 0){
            resultMap.put("success",false);
            resultMap.put("list", new ArrayList<ProductType>());
            renderJSON(resultMap);
        }
        resultMap.put("success",true);
        resultMap.put("list",secondLevel);
        renderJSON(resultMap);
    }

}
